package com.example.uhf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.apkfuns.logutils.LogUtils;
import com.apkfuns.logutils.file.LogFileEngine;
import com.apkfuns.logutils.file.LogFileParam;
import com.rscja.utility.StringUtility;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.TabActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import cn.com.example.rfid.driver.Driver;
import cn.com.example.rfid.driver.RfidDriver;

public class ConnectActivity extends TabActivity {
	public static String mStopTime = "10";
	public static boolean isStopTime = false;

	private boolean loopFlag = false;
	Driver driver ;
	String path = "/mnt/sdcard/";
	Handler handler;
	ListView mListView;
	TextView tv_count, sum, tV_time;
	CheckBox cb_sound, cb_AcsHex;
	private ArrayList<HashMap<String, String>> tagList =new ArrayList<HashMap<String,String>>();
	HashMap<String, String> hmap = new HashMap<>();
	HashMap<String, Integer> map = new HashMap<String, Integer>(100000);
	//生成一个ArrayList类型的变量list 
	SimpleAdapter adapter;
	int iIndex = 0;
	TabHost tabHost;
	int Ct = 0;
	int flag = 0;
	Button BtInventory;
	Timer stoptimer = new Timer();
	Handler stopHandler;

	Timer soundTimer = new Timer();
	private SoundTimerTask soundTimerTask;
	Handler soundTimerHandler;
	int 	soundCnt = 0;

	int tct = 0;
	int GetCnt = 0;
	//long curDate;
	long curDate, lastData;
	SimpleDateFormat sdfhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	int soundFlag = 0;												//读卡响声
	private SoundPool soundPool;
	private int soundId;

	class SoundTimerTask extends TimerTask {
		@Override
		public void run(){
			if (soundCnt < 5)
			{
				soundCnt++;

				if(1 == soundFlag){
					soundPool.play(soundId, 1, 1, 0, 0, 1);
				}
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_titlelayout);
		mListView = (ListView) findViewById(R.id.listView1);		
		driver = new RfidDriver();

		//adapter = new SimpleAdapter(this, tagList, R.layout.item,
				//new String[] { "sn", "epc", "count"/*, "rssi"*/}, new int[] {
				//		R.id.sn, R.id.epc, R.id.count/*, R.id.rssi*/});
		adapter = new SimpleAdapter(this, tagList, R.layout.item,
		new String[] { "sn", "epc", "count", "rssi"}, new int[] {
				R.id.sn, R.id.epc, R.id.count, R.id.rssi});

		/*   Create by Xysh */
		LogUtils.getLogConfig()
				.configAllowLog(true)
				.configTagPrefix("LogUtils")
				.configShowBorders(true);
		LogUtils.getLog2FileConfig()
				.configLog2FileEnable(true)
				.configLog2FilePath(path)
				.configLog2FileNameFormat("%d{yyyyMMdd}.txt")
				.configLogFileEngine(new LogFileEngine() {
			@Override
			public void writeToFile(File file, String s, LogFileParam logFileParam) {
				FileOutputStream Outputs;

				if(!file.exists()) {
					try {
						file.createNewFile();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				try {
					Outputs = new FileOutputStream(file, true);
					if(Outputs != null){
						try {
							Outputs.write(("----------------------------------------------------------------------------------------" + "\r\n").getBytes());
							Outputs.write((sdfhms.format(System.currentTimeMillis()) +"        " + s + "\r\n").getBytes());
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}catch (IOException e){
					e.printStackTrace();
				}
			}
		});

		tabHost = (TabHost)findViewById(android.R.id.tabhost);
		tabHost.setup();      
		
		tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("盘点").setContent(
						R.id.tab1));
		
		tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("设置").setContent(
						new Intent(this, SettingActivity.class)));

		tv_count = (TextView)findViewById(R.id.Epc_count);
		
		sum = (TextView)findViewById(R.id.sum);
		BtInventory = (Button)findViewById(R.id.readrfid);
		tV_time = (TextView)findViewById(R.id.tV_time);
		cb_sound = (CheckBox)findViewById(R.id.cB_Sound);
		cb_sound.setChecked(true);
		soundFlag = 1;
		cb_AcsHex = (CheckBox)findViewById(R.id.cb_AcsToHex);
		cb_AcsHex.setChecked(true);

		//soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
		//soundId = soundPool.load(this, R.raw.beep, 1);

		soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
		soundId = soundPool.load("/system/media/audio/ui/VideoRecord.ogg", 0);

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				addEPCToList(msg.obj + "", hmap, tagList);
				long nowTime = System.currentTimeMillis();
				long timedate = nowTime - lastData;
				tV_time.setText(String.valueOf(timedate));


				adapter.notifyDataSetChanged();
				Ct++;
				tv_count.setText("" + hmap.size());
				sum.setText(""+Ct);
			}
		};


		stopHandler = new Handler(){
			@Override
			public void handleMessage(Message msg){
				//DoWithEpc("" + msg.obj);
				if (msg.obj == "start")
				{
					BtInventory.setText("读取RFID");
				}
			}
		};
		
		BtInventory.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			switch(flag) {
			case 0:
				tagList.clear();
				mListView.setAdapter(adapter);
				map.clear();
				hmap.clear();
				iIndex = 0;
				Ct = 0;
				sum.setText("");
				tv_count.setText("");
				driver.readMore(0);
				new TagThread().start();
				loopFlag = true;
				lastData = System.currentTimeMillis();

				if(soundTimer == null){
					soundTimer = new Timer();
				}
				if(soundTimer != null && soundTimerTask != null){
					soundTimerTask.cancel();
				}
				soundTimerTask = new ConnectActivity.SoundTimerTask();
				soundTimer.schedule(soundTimerTask, 0, 150);
				soundCnt = 5;

				BtInventory.setText("停止识别");
				flag = 1;
				break;
			case 1:
				iIndex = 0;
				stopInventory();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				BtInventory.setText("读取RFID");

				if(soundTimer != null && soundTimerTask != null){
					soundTimerTask.cancel();
				}

				flag = 0;
				GetCnt = 0;
				break;
			default:
				break;
			}

		}
	});

	findViewById(R.id.cleardata).setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			tagList.clear();
			mListView.setAdapter(adapter);
			map.clear();
			hmap.clear();
			iIndex = 0;
			Ct = 0;
			sum.setText("");
			tv_count.setText("");
		}
	});

	cb_sound.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if(cb_sound.isChecked()){
				soundFlag = 1;
			}else {
				soundFlag = 0;
			}
		}
	});

	}

	/**
	 * 停止识别
	 */
	private void stopInventory() {

		if (loopFlag) {

			loopFlag = false;

			driver.stopRead();

		}
	}


	public static String stringToAscii(String value)
	{
		String res = "";


		int[] toint = new int[20];

		int max = value.length();
		for(int i = 0; i < max/2; i++)
		{
			String str = value.substring(2*i, (2*i)+2);
			toint[i] = Integer.valueOf(str);
			char ch = (char)toint[i];
			res = res + ch;
		}
		return res;
	}
	public static int hexStringToAlgorism(String hex) {
		hex = hex.toUpperCase();
		int max = hex.length();
		int result = 0;
		for (int i = max; i > 0; i--) {
			char c = hex.charAt(i - 1);
			int algorism = 0;
			if (c >= '0' && c <= '9') {
				algorism = c - '0';
			} else {
				algorism = c - 55;
			}
			result += Math.pow(16, max - i) * algorism;
		}
		return result;
	}


	public static String AsciiStringToString(String content) {
		String result = "";
		int length = content.length() / 2;
		for (int i = 0; i < length; i++) {
			String c = content.substring(i * 2, i * 2 + 2);
			int a = hexStringToAlgorism(c);
			char b = (char) a;
			String d = String.valueOf(b);
			result += d;
		}
		return result;
	}

	private void addEPCToList(String epc, HashMap<String, String> hmap, ArrayList<HashMap<String, String>> tagList) {
		LogUtils.i("???epc ==	" + epc);
		int Hb = 0;
		int Lb = 0;
		int rssi = 0;
		String[] tmp = new String[3];
		HashMap<String, String> temp = new HashMap<>();
		String text = epc.substring(4);
		String len = epc.substring(0, 2);
		int epclen = (Integer.parseInt(len, 16) / 8) * 4;
		tmp[0] = text.substring(epclen, text.length() - 6);
		tmp[1] = text.substring(0, text.length()-6);
		tmp[2] = text.substring(text.length() - 6, text.length() - 2);

		if(4 != tmp[2].length()){
			tmp[2] = "0000";
		} else {
			Hb = Integer.parseInt(tmp[2].substring(0,2), 16);
			Lb = Integer.parseInt(tmp[2].substring(2, 4), 16);
			rssi = ((Hb - 256 + 1) * 256 + (Lb - 256)) / 10;
		}

		if(1 == soundFlag){
			//soundPool.play(soundId, 1, 1, 0, 0, 1.2f);
			soundCnt = 0;
		}

		if(cb_AcsHex.isChecked()){

		}else{
			tmp[1] = AsciiStringToString(tmp[1]);
		}

		int count = 0;
		temp.put("epc", tmp[1]);
		if(hmap.containsKey(tmp[1])){
			String strTemp = hmap.get(tmp[1]);
			if(null != strTemp){
				int sn = Integer.valueOf(strTemp.split(",")[1]);
				count = Integer.valueOf(strTemp.split(",")[0]) + 1;
				temp.put("sn", ""+sn);
				temp.put("count", ""+ count);
				temp.put("rssi", ""+ rssi);
				hmap.put(tmp[1], String.valueOf(count) + "," + String.valueOf(sn) + "," + rssi);
				tagList.set(sn, temp);
			}
		}else {
			hmap.put(tmp[1], "1," + iIndex + "," + rssi);
			temp.put("sn", ""+iIndex);
			temp.put("count", "1");
			temp.put("rssi", ""+ rssi);
			tagList.add(temp);
			//mListView.setAdapter(adapter);
			iIndex++;
		}
	}

	class TagThread extends Thread {

		private int mBetween = 0;

		public TagThread() {

		}

		public void run() {

			while (loopFlag) {
				if (isStopTime == true) {
					curDate = System.currentTimeMillis();
					long diff = curDate - lastData;

					if ((mStopTime == null) || mStopTime.isEmpty()) {
						mStopTime = "0";
					}

					int stopTime = Integer.parseInt(mStopTime);
					if (diff > (stopTime)) {
						stopInventory();
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						flag = 0;
						Message msg = stopHandler.obtainMessage();
						msg.obj = "start";
						stopHandler.sendMessage(msg);
						break;
					}
				}

				try {
					String[] strEpc1 = {driver.GetBufData()};
					String strEpc = strEpc1[0];
//					LogUtils.i("driver.GetBufData()	" + strEpc);
					if (!StringUtility.isEmpty(strEpc)) {
						String first = strEpc.substring(0,5);
						if (first.equals("Temp:")) {
							// 温度信息
							String Strvalue = strEpc.substring(5);
							int itemp = Integer.parseInt(Strvalue);
							float  ftemp = itemp;
							ftemp = ftemp / 100;
							Strvalue = Float.toString(ftemp);
						} else {
							// 读卡信息
							Message msg = handler.obtainMessage();
							msg.obj = strEpc;
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				try {
					sleep(mBetween);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	}


	/*固件版本*/
	private void Um7Fw() {
		String Fw_buffer;		 
		Fw_buffer = driver.readUM7fwOnce();

		if(Fw_buffer.equals("-1000")){
			Toast.makeText(ConnectActivity.this, "设备未连接", Toast.LENGTH_SHORT).show();
			return;
		}

		if(Fw_buffer.equals("-1020")){
			Toast.makeText(ConnectActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
			return;
		}

		StringBuilder fw = new StringBuilder(getDesignatedDecimalData(Fw_buffer));
		fw.insert(0, "固件版本号：");
//		fw.insert(8, ".");
//		fw.insert(11, ".");
		String Sfw = fw.toString();
		
		Toast.makeText(ConnectActivity.this, Sfw, Toast.LENGTH_SHORT).show();

	}
		
	/*	硬件版本*/
	private void Um7Hw() {
		String text;
		text = driver.readUM7hwOnce();

		if(text.equals("-1000")){
			Toast.makeText(ConnectActivity.this, "设备未连接", Toast.LENGTH_SHORT).show();
			return;
		}

		if(text.equals("-1020")){
			Toast.makeText(ConnectActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
			return;
		}

		StringBuilder hw = new StringBuilder(getDesignatedDecimalData(text));

		hw.insert(0, "硬件版本号：");
//		hw.insert(8, ".");
//		hw.insert(11, ".");
		String Shw = hw.toString();

		Toast.makeText(ConnectActivity.this, Shw, Toast.LENGTH_SHORT).show();
	}

	// Get ID
	private void Um7GetModuleID() {
		String text;
		text = driver.GetModuleID();
		//text = driver.GetAccessControlEAS();
		//text = driver.GetAccessControlTriggerPara();
		//text = driver.GetAccessControlNumberOfPeople();

		if(text.equals("-1000")){
			Toast.makeText(ConnectActivity.this, "设备未连接", Toast.LENGTH_SHORT).show();
			return;
		}

		if(text.equals("-1020")){
			Toast.makeText(ConnectActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
			return;
		}

		String Shw = "模块ID：" + text;
		Toast.makeText(ConnectActivity.this, Shw, Toast.LENGTH_SHORT).show();
	}

	/* 开启距离测试模式 */
	private void StartRangeTest() {

		// 1. 设置自适应模式, 不掉电保存
		driver.Inventory_Model_Set(4, false);

		// 2. 设置发射功率为读功率=33dBm，写功率=33dBm
		driver.SetTxPower(33, 33, 1,1);
	}

	/* 开启群读测试模式 */
	private void StartGroupInventoryTest() {

		// 1. 设置模式4, 不掉电保存
		driver.Inventory_Model_Set(3, false);

		// 2. 设置区域为USA
		driver.SetRegion(0x08);

		// 3. 设置发射功率为读功率=33dBm，写功率=33dBm
		driver.SetTxPower(33, 33, 1,1);
	}

	/* 恢复出厂设置 */
	private void RestoreFactorySettings() {

		driver.RestoreFactory();
	}

	//底层固件版本进制转换拼接
	private String getDesignatedDecimalData(String hexString) {
		StringBuilder version = new StringBuilder();
		int n = 0;
		for (int i = 0; i < 3; i++) {
			int vals = Integer.parseInt(hexString.substring(n, n + 2), 16);
			String val = i < 2 ? vals + "." : vals + "";
			version.append(val);
			n += 2;
		}
		return version.toString();
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		menu.add(1, Menu.FIRST, 1, "硬件版本");
		menu.add(1, 2, 2, "固件版本");
		menu.add(1, 3, 3, "模块ID");
		menu.add(1, 4, 4, "距离测试");
		menu.add(1, 5, 5, "群读测试");
		menu.add(1, 6, 6, "出厂设置");
		return true;
	}

   @Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch(item.getItemId()){
			case 1:            //Menu.FIRST对应itemid为1
				Um7Hw();
				break;
			case 2:
				Um7Fw();
				break;
			case 3:
				Um7GetModuleID();
				break;
			case 4:
				StartRangeTest();
				Toast.makeText(ConnectActivity.this, "开启距离测试", Toast.LENGTH_SHORT).show();
				break;
			case 5:
				StartGroupInventoryTest();
				Toast.makeText(ConnectActivity.this, "开启群读测试", Toast.LENGTH_SHORT).show();
				break;
			case 6:
				RestoreFactorySettings();
				Toast.makeText(ConnectActivity.this, "恢复出厂设置", Toast.LENGTH_SHORT).show();
				break;
			default:
				return false;
		}

	   return true;
	}

	@Override
	protected void onDestroy(){
	    super.onDestroy();
        loopFlag = false;
        driver.stopRead();
    }

}
